package io.finer.erp.jeecg.bas.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.BasCustomerAddress;
import io.finer.erp.jeecg.bas.entity.ZrkCreditLimit;
import io.finer.erp.jeecg.bas.entity.ZrkCreditLog;
import io.finer.erp.jeecg.bas.service.IBasCustomerAddressService;
import io.finer.erp.jeecg.bas.service.IZrkCreditLimitService;
import io.finer.erp.jeecg.bas.service.IZrkCreditLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 客户授信额度管理
 * @Author: jeecg-boot
 * @Date:   2020-10-09
 * @Version: V1.0
 */
@Api(tags="客户授信额度管理")
@RestController
@RequestMapping("/bas/zrkCreditLimit")
@Slf4j
public class ZrkCreditLimitController extends JeecgController<ZrkCreditLimit, IZrkCreditLimitService> {
	@Autowired
	private IZrkCreditLimitService zrkCreditLimitService;
	
	@Autowired
	private IBasCustomerAddressService basCustomerAddressService;
	
	@Autowired
	private IZrkCreditLogService zrkCreditLogService;
	
	/**
	 * 分页列表查询
	 *
	 * @param zrkCreditLimit
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-分页列表查询")
	@ApiOperation(value="客户授信额度管理-分页列表查询", notes="客户授信额度管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkCreditLimit zrkCreditLimit,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZrkCreditLimit> queryWrapper = QueryGenerator.initQueryWrapper(zrkCreditLimit, req.getParameterMap());
		Page<ZrkCreditLimit> page = new Page<ZrkCreditLimit>(pageNo, pageSize);
		IPage<ZrkCreditLimit> pageList = zrkCreditLimitService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 * @description 根据客户手机号查询客户授信情况,返回到手机端展示客户固定额度、临时额度
	 * @param mobile 客户手机号
	 * @param req
	 * @return
	 */
	@AutoLog(value = "根据客户手机号查询客户授信情况")
	@ApiOperation(value="根据客户手机号查询客户授信情况", notes="根据客户手机号查询客户授信情况")
	@GetMapping(value = "/queryCustomerCreditInfo")
	public Result<?> queryCustomerCreditInfo(@RequestParam(name="mobile",required=true) String mobile) {
		//根据客户手机号查询客户信息
		QueryWrapper<BasCustomerAddress> queryWrapper=new QueryWrapper<BasCustomerAddress>();
		queryWrapper.eq("phone_no",mobile);
		List<BasCustomerAddress> list=basCustomerAddressService.list(queryWrapper);
		ZrkCreditLimit zrkCreditLimit=new ZrkCreditLimit();
		if(null!=list&&list.size()>0) {
			//查询客户ID
			QueryWrapper<ZrkCreditLimit> qw=new QueryWrapper<ZrkCreditLimit>();
			qw.eq("cus_id", list.get(0).getCustomerId());
			zrkCreditLimit=zrkCreditLimitService.getOne(qw.last("LIMIT 1"));
		}
		return Result.ok(zrkCreditLimit);
	}
	
	/**
	 * @description 用户商城使用账期支付后更新客户额度信息
	 * @param zrkCreditLimit
	 * @return
	 */
	@AutoLog(value = "更新客户额度信息")
	@ApiOperation(value="更新客户额度信息", notes="更新客户额度信息")
	@PutMapping(value = "/afterBuy")
	public Result<?> afterBuy(@RequestParam(name="creditAmount",required=true) String creditAmount,@RequestParam(name="mobile",required=true) String mobile,@RequestParam(name="orderCode",required=true) String orderCode) {
		//根据客户手机号查询客户信息
		QueryWrapper<BasCustomerAddress> cusQw=new QueryWrapper<BasCustomerAddress>();
		cusQw.eq("phone_no", mobile);
		List<BasCustomerAddress> list=basCustomerAddressService.list(cusQw);
		String customerId="0";
		if(null!=list&&list.size()>0) {
			customerId=list.get(0).getCustomerId();
		}
		QueryWrapper<ZrkCreditLimit> queryWrapper=new QueryWrapper<ZrkCreditLimit>();
		queryWrapper.eq("cus_id", customerId);
		ZrkCreditLimit zcl=zrkCreditLimitService.getOne(queryWrapper);
		ZrkCreditLog zrkCredLog=new ZrkCreditLog();
		BigDecimal ca=new BigDecimal(creditAmount);
		//判断客户固定额度是否足以支付该笔订单
		if(ca.compareTo(zcl.getRemainAmount())!=1) {
			//固定额度足以支付，无须考虑临时额度支付
			BigDecimal ra=zcl.getRemainAmount().subtract(ca);
			//防止因为减法运算出现负数的情况
			if(ra.compareTo(BigDecimal.ZERO)==-1) {
				ra=BigDecimal.ZERO;
			}
			zcl.setRemainAmount(ra);
			//记录变更日志
			zrkCredLog.setCreateBy("admin");
			zrkCredLog.setCreateTime(DateUtils.getDate());
			zrkCredLog.setCreditLimitAmount(ca);
			zrkCredLog.setCusId(zcl.getCusId());
			zrkCredLog.setOrderCode(orderCode);
			zrkCredLog.setStartDate(zcl.getStartDate());
			zrkCredLog.setEndDate(zcl.getEndDate());
			//临时额度未使用
			zrkCredLog.setTemporyQuota(BigDecimal.ZERO);
			zrkCredLog.setRemark("商城订单号："+orderCode+",采用固额支付");
			zrkCreditLogService.save(zrkCredLog);
			zrkCreditLimitService.updateById(zcl);
			Result.ok("更新额度信息成功!");
		}else{
			//固定额度不足时判断临时额度+固定额度是否足够支付该笔订单
			BigDecimal total=zcl.getRemainAmount().add(zcl.getTemporaryRemain());
			if(total.compareTo(ca)!=-1&&zcl.getRemainAmount().compareTo(BigDecimal.ZERO)==1) {
				//支付方式为：固定额度+临时额度
				BigDecimal tAmount=ca.subtract(zcl.getRemainAmount());//临时额度变动数量
				zcl.setRemainAmount(BigDecimal.ZERO);
				BigDecimal tr=zcl.getTemporaryRemain().subtract(tAmount);
				//防止负数的情况出现
				if(tr.compareTo(BigDecimal.ZERO)==-1) {
					tr=BigDecimal.ZERO;
				}
				zcl.setTemporaryRemain(tr);
				//记录变更日志
				zrkCredLog.setCreateBy("admin");
				zrkCredLog.setCreateTime(DateUtils.getDate());
				zrkCredLog.setCreditLimitAmount(zcl.getRemainAmount());
				zrkCredLog.setCusId(zcl.getCusId());
				zrkCredLog.setOrderCode(orderCode);
				zrkCredLog.setStartDate(zcl.getStartDate());
				zrkCredLog.setEndDate(zcl.getEndDate());
				//临时额度未使用
				zrkCredLog.setTemporyQuota(tAmount);
				zrkCredLog.setRemark("商城订单号："+orderCode+",采用固额+临额支付");
				zrkCreditLogService.save(zrkCredLog);
				zrkCreditLimitService.updateById(zcl);
				Result.ok("更新额度信息成功!");
			}else if(zcl.getRemainAmount().compareTo(BigDecimal.ZERO)==0) {
				//固定额度为0,判断临额是否足够支付
				if(zcl.getTemporaryRemain().compareTo(ca)!=-1) {
					//临额足够支付，判断临额有效期
					if(DateUtils.belongCalendar(DateUtils.getDate(), zcl.getStartDate(), zcl.getEndDate())) {
						BigDecimal tr2=zcl.getTemporaryRemain().subtract(ca);
						//防止负数的情况出现
						if(tr2.compareTo(BigDecimal.ZERO)==-1) {
							tr2=BigDecimal.ZERO;
						}
						zcl.setTemporaryRemain(tr2);
						//记录日志
						//记录变更日志
						zrkCredLog.setCreateBy("admin");
						zrkCredLog.setCreateTime(DateUtils.getDate());
						zrkCredLog.setCreditLimitAmount(BigDecimal.ZERO);
						zrkCredLog.setCusId(zcl.getCusId());
						zrkCredLog.setOrderCode(orderCode);
						zrkCredLog.setStartDate(zcl.getStartDate());
						zrkCredLog.setEndDate(zcl.getEndDate());
						zrkCredLog.setTemporyQuota(ca);
						zrkCredLog.setRemark("商城订单号："+orderCode+",采用临额支付");
						zrkCreditLogService.save(zrkCredLog);
						zrkCreditLimitService.updateById(zcl);
						Result.ok("更新额度信息成功!");
					}else {
						Result.error("固额不足，临额失效!");
					}
				}else {
					//临额不足以支付
					Result.error("临额/固额不足!");
				}
			}else {
				//额度补足
				Result.error("额度不足!");
			}
		}
//		zrkCreditLimitService.updateById(zcl);
//		return null;
		return Result.ok("更新额度信息成功!");
	}
	
	/**
	 *   添加
	 *
	 * @param zrkCreditLimit
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-添加")
	@ApiOperation(value="客户授信额度管理-添加", notes="客户授信额度管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkCreditLimit zrkCreditLimit) {
		zrkCreditLimitService.save(zrkCreditLimit);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param zrkCreditLimit
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-编辑")
	@ApiOperation(value="客户授信额度管理-编辑", notes="客户授信额度管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkCreditLimit zrkCreditLimit) {
		zrkCreditLimitService.updateById(zrkCreditLimit);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-通过id删除")
	@ApiOperation(value="客户授信额度管理-通过id删除", notes="客户授信额度管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkCreditLimitService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-批量删除")
	@ApiOperation(value="客户授信额度管理-批量删除", notes="客户授信额度管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkCreditLimitService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "客户授信额度管理-通过id查询")
	@ApiOperation(value="客户授信额度管理-通过id查询", notes="客户授信额度管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZrkCreditLimit zrkCreditLimit = zrkCreditLimitService.getById(id);
		if(zrkCreditLimit==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(zrkCreditLimit);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param zrkCreditLimit
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZrkCreditLimit zrkCreditLimit) {
        return super.exportXls(request, zrkCreditLimit, ZrkCreditLimit.class, "客户授信额度管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZrkCreditLimit.class);
    }

}
